﻿using System.Collections.Generic;
using DevExpress.XtraEditors;
using EkStudio.Com.UI.Interface;
using EkStudio.com.bean.xml.BillDictionary;
using System.Windows.Forms;
using EkStudio.com.common.unit;
using System;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.bean.xml.reflection.JAXB;
using System.Xml;
using System.ComponentModel;
using EkStudio.com.ui.unitbill.property;
using EkStudio.com.ui.unitbill.property.Event;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.common.clipboard;

namespace EkStudio.com.ui.unitbill
{
    public partial class BillDictionaryUnitPanel : XtraUserControl, ProjectUnitBillInterface
    {

        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(BillModuleControl));

        private bool readOnly = false;
        private bool save = true;
        private ProjectRootPanel RootPanel = null;
        //private ProjectUnitBillInterface ParentUnit = null;
        private List<ProjectUnitBillInterface> SubjectUnit = new List<ProjectUnitBillInterface>();//子面板

        private BillDicModuleItem dicBean = null;

        private ModuleBean BeanInfo = null;

        private bool ReLoadMenu = false;

        private ModuleUiFieldProperty FieldProperty = null;

        private bool moveing = false;


        public BillDictionaryUnitPanel(ProjectRootPanel root, BillDicModuleItem bean, bool read)
        {
            InitializeComponent();
            readOnly = read;
            RootPanel = root;
            dicBean = bean;
            InitForm();

        }

        private void InitForm()
        {
            BeanInfo = new ModuleBean(dicBean);
            ModulePropertyGrid.SelectedObject = BeanInfo;

            FieldProperty = new ModuleUiFieldProperty(dicBean, RootPanel, this);
            FieldProperty.Dock = DockStyle.Fill;
            FieldProperty.Visible = false;
            FieldProperty.CaptionChanged += FieldCaptionChanged;
            FieldProperty.LinkerChange += LinkerChanged;

            PropFieldPanel.Controls.Add(FieldProperty);

            ShowFieldGroup();
        }



        private void ShowFieldGroup()
        {
            if (dicBean.FieldsProperties == null)
            {
                dicBean.FieldsProperties = new BillDicModuleFieldsRoot();
            }
            if (dicBean.FieldsProperties.Fields == null) dicBean.FieldsProperties.Fields = new List<BillUiFieldsItem>();
            FieldListView.Items.Clear();

            if (dicBean.FieldsProperties.Fields.Count > 0)
            {
                for (int i = 0; i < dicBean.FieldsProperties.Fields.Count; i++)
                {
                    BillUiFieldsItem field = dicBean.FieldsProperties.Fields[i];
                    ListViewItem ViewIt = new ListViewItem(field.Caption, 1);
                    ViewIt.Tag = field;
                    FieldListView.Items.Add(ViewIt);
                }
            }
        }



        #region 接口属性

        public string BillKey
        {
            get
            {
                return dicBean.getKey();
            }
        }

        public bool isSubUnitBill
        {
            get
            {
                return false;
            }
        }

        public ProjectUnitBillInterface ParentPage
        {
            get
            {
                return null;
            }

            set
            {

            }
        }

        public bool ReadOnly
        {
            get
            {
                return readOnly;
            }

            set
            {
                readOnly = value;
            }
        }
        private bool isSubSaveStatus()
        {
            bool result = true;
            if (SubjectUnit.Count > 0)
            {
                for (int i = 0; i < SubjectUnit.Count; i++)
                {
                    if (!SubjectUnit[i].SaveStatus)
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }


        public bool SaveStatus
        {
            get { return save; }
            set { save = value; RootPanel.SaveStatus = value; }
        }

        public List<ProjectUnitBillInterface> SubjectPage
        {
            get { return SubjectUnit; }
        }

        public void AddSubjectBill(ProjectUnitBillInterface bill)
        {
            if (!SubjectUnit.Contains(bill))
            {
                bill.ParentPage = this;
                SubjectUnit.Add(bill);
            }
        }

        public bool close()
        {
            bool result = true;
            if (!save || !isSubSaveStatus())
            {
                DialogResult dialog = XtraMessageBox.Show("当前数据已更改是否保存?", "提示", MessageBoxButtons.YesNoCancel);
                if (dialog == DialogResult.Yes)
                {
                    saveData(true);
                    result = true;
                }
                else if (dialog == DialogResult.No)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }

            if (result)
            {
                //释放模块占用
                try
                {
                    RootPanel.Http.ReleaseModule("Dic_" + dicBean.getKey(), dicBean.getCaption(), ProjectUtil.TYPE_DIC_MODULE);
                }
                catch (Exception e)
                {
                    RootPanel.AddConsoleText("页面关闭失败", true);
                    logger.Error("页面关闭失败", e);
                }

            }

            return result;
        }

        public bool ContainSubject(ProjectUnitBillInterface bill)
        {
            return SubjectUnit.Contains(bill);
        }

        public void RemoveSubjectBill(ProjectUnitBillInterface bill)
        {
            if (ContainSubject(bill))
            {
                bill.ParentPage = null;
                SubjectUnit.Remove(bill);
            }
        }

        public void saveData(bool updateParent)
        {
            if (!readOnly && (!save || !isSubSaveStatus()))
            {
                if (!isSubSaveStatus())
                {
                    //先保存子表
                    foreach (ProjectUnitBillInterface subPage in SubjectUnit)
                    {
                        subPage.saveData(false);
                    }
                }
                dicBean.autoInitDataSource();
                dicBean.autoInitLanguage(RootPanel.ProjectVersion);
                dicBean.RootProperties.RootVersion = BeanUtil.VERSION;
                dicBean.RootProperties.OwnerProperties.LastMender = RootPanel.UserInfo.UserName;
                dicBean.RootProperties.OwnerProperties.LastModified = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");


                JAXBContext<BillDicModuleItem> jaxb = new JAXBContext<BillDicModuleItem>();

                string xml = jaxb.marshal(dicBean, true);

                string result = RootPanel.Http.SaveXmlBean(dicBean.getKey(), ProjectUtil.TYPE_DIC_MODULE, xml);

                XmlDocument docXml = new XmlDocument();
                try
                {
                    docXml.LoadXml(result);
                    XmlElement root = docXml.DocumentElement;
                    XmlNode node = root.SelectSingleNode("result");
                    if (node.InnerText == "0")
                    {
                        RootPanel.AddConsoleText(string.Format("保存字典[{0}]成功", dicBean.getCaption()), false);
                    }
                    else
                    {
                        RootPanel.AddConsoleText(string.Format("保存字典[{0}]失败", dicBean.getCaption()), false);
                    }
                }
                catch (Exception e)
                {
                    RootPanel.AddConsoleText(string.Format("保存字典[{0}]失败", dicBean.getCaption()), false);
                    logger.Error("保存失败", e);
                }
                if (ReLoadMenu) RootPanel.InitMenu();
            }

            save = true;
            if (updateParent) RootPanel.SaveStatus = true;
            ModulePropertyGrid.Refresh();
        }


        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="clazz">复制后的clazz</param>
        /// <returns></returns>
        public bool Copy(out object clazz)
        {
            bool val = false;
            clazz = null;

            return val;
        }

        #endregion




        private class ModuleBean
        {
            private BillDicModuleItem item = null;
            public ModuleBean(BillDicModuleItem info)
            {
                item = info;
            }

            [Description("字典中文标签")]
            public string Caption
            {
                get { return item.getCaption(); }
                set { item.RootProperties.Caption = value; }
            }

            public string Key
            {
                get { return item.RootProperties.Key; }
                set { }
            }

            public string Creater
            {
                get { return item.RootProperties.OwnerProperties.Creater; }
                set { }
            }

            public string Created
            {
                get { return item.RootProperties.OwnerProperties.Created; }
                set { }
            }

            public string LastMender
            {
                get { return item.RootProperties.OwnerProperties.LastMender; }
                set { }
            }

            public string LastModified
            {
                get { return item.RootProperties.OwnerProperties.LastMender; }
                set { }
            }

        }
        



        private void ModulePropertyGrid_CellValueChanged(object sender, DevExpress.XtraVerticalGrid.Events.CellValueChangedEventArgs e)
        {
            if (e.Row.Properties.FieldName == "Caption")//修改模块标签
            {
                ReLoadMenu = true;
            }
            SaveStatus = false;
        }

        private void FieldListView_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (moveing) return;
            PropertyTabPage.SelectedTabPageIndex = 0;
            if (FieldListView.SelectedItems.Count > 0)
            {
                if (FieldListView.SelectedItems.Count == 1)
                {
                    BillUiFieldsItem field = FieldListView.SelectedItems[0].Tag as BillUiFieldsItem;
                    if (field != null)
                    {
                        BillUiFieldToProperty prop = new BillUiFieldToProperty(field, null);
                        FieldProperty.SelectField = prop;
                        
                    }
                }else
                {
                    BillUiFieldToProperty[] groups = new BillUiFieldToProperty[FieldListView.SelectedItems.Count];
                    for (int i = 0; i < FieldListView.SelectedItems.Count; i++)
                    {
                        ListViewItem vIt = FieldListView.SelectedItems[i];
                        object tag = vIt.Tag;
                        groups[i] = new BillUiFieldToProperty((BillUiFieldsItem)tag, null);
                    }
                    FieldProperty.SelectFields = groups;
                }
                FieldProperty.Visible = true;
            }
            else
            {
                FieldProperty.Visible = false;
            }

                
        }


        private void LinkerChanged(object sender, PropertyDataEvent e)
        {

        }

        private void FieldCaptionChanged(object sender, PropertyDataEvent e)
        {
            if (FieldListView.SelectedItems.Count == 1)
            {
                ListViewItem item = FieldListView.SelectedItems[0];
                item.Text = (string)e.Value;
            }
        }

        private void FieldListView_Click(object sender, EventArgs e)
        {
            FieldListView_SelectedIndexChanged(sender, e);
        }
        private void FieldListView_KeyDown(object sender, KeyEventArgs e)
        {

        }

        /// <summary>
        /// 菜单新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldPopNewNode_Click(object sender, EventArgs e)
        {
            if (readOnly) return;

            BillUiFieldsItem field = new BillUiFieldsItem();
            field.DataProperty = new BillUiFieldsDataProperty();
            field.EditBorder = new BillUiFieldsEditBorderProperty();
            field.EditProperty = new BillUiFieldsEditProperty();
            field.FormulaProperty = new BillUiFieldsFormulaProperty();
            field.ViewBorder = new BillUiFieldsViewBorderProperty();
            dicBean.FieldsProperties.addNode(field, dicBean);
            ListViewItem it = new ListViewItem(field.Caption, 1);
            it.Tag = field;
            FieldListView.Items.Add(it);
            it.Selected = true;
            SaveStatus = false;
        }

        private void FieldPopDeleteNode_Click(object sender, EventArgs e)
        {
            if (readOnly) return;
            if (FieldListView.SelectedItems.Count == 1)
            {
                DialogResult DR = XtraMessageBox.Show("您确认要删除当前选中字段吗?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (DR == DialogResult.Yes)
                {
                    ListViewItem it = FieldListView.SelectedItems[0];
                    BillUiFieldsItem field = (BillUiFieldsItem)it.Tag;
                    dicBean.FieldsProperties.removeNode(field);
                    it.Tag = null;
                    FieldListView.Items.Remove(it);
                    field = null;
                    it = null;
                    SaveStatus = false;
                    FieldProperty.Visible = false;
                }
            }
        }

        private void FieldPopCopyNode_Click(object sender, EventArgs e)
        {
            if (FieldListView.SelectedItems.Count > 0)
            {
                bool sccuess = true;
                BillUiFieldsItem[] fields = new BillUiFieldsItem[FieldListView.SelectedItems.Count];
                int i = 0;
                foreach (ListViewItem it in FieldListView.SelectedItems)
                {
                    try
                    {
                        BillUiFieldsItem Cp = (BillUiFieldsItem)((BillUiFieldsItem)it.Tag).Clone();
                        fields[i] = Cp;
                    }
                    catch (Exception ee)
                    {
                        logger.Error("字段不支持复制", ee);
                        RootPanel.AddConsoleText("字段不支持复制", true);
                        sccuess = false;
                    }
                    i++;
                }
                if (sccuess)
                {
                    JClipboard.copy(fields);
                    RootPanel.AddConsoleText("复制字段Len==" + fields.Length, false);
                }
            }
        }

        private void FieldPopPasteNode_Click(object sender, EventArgs e)
        {
            if (readOnly) return;
            if (!JClipboard.ContainData()) return;
            if (JClipboard.Paste()[0] is BillUiFieldsItem)
            {
                foreach (BillUiFieldsItem field in JClipboard.Paste())
                {
                    dicBean.FieldsProperties.addNode(field, dicBean);
                    ListViewItem it = new ListViewItem(field.Caption, 1);
                    it.Tag = field;
                    FieldListView.Items.Add(it);
                }
                SaveStatus = false;
                JClipboard.Clear();
            }
        }

        private void FieldPopCutNode_Click(object sender, EventArgs e)
        {
            if (readOnly) return;
            if (FieldListView.SelectedItems.Count > 0)
            {
                moveing = true;
                bool sccuess = true;
                BillUiFieldsItem[] fields = new BillUiFieldsItem[FieldListView.SelectedItems.Count];
                int i = 0;
                foreach (ListViewItem it in FieldListView.SelectedItems)
                {
                    try
                    {
                        BillUiFieldsItem Cp = (BillUiFieldsItem)((BillUiFieldsItem)it.Tag).Clone();
                        fields[i] = Cp;
                    }
                    catch (Exception ee)
                    {
                        logger.Error("字段不支持复制", ee);
                        RootPanel.AddConsoleText("字段不支持复制", true);
                        sccuess = false;
                    }
                    i++;
                }
                if (sccuess)
                {
                    JClipboard.copy(fields);
                    foreach (ListViewItem it in FieldListView.SelectedItems)
                    {
                        BillUiFieldsItem field = it.Tag as BillUiFieldsItem;
                        dicBean.FieldsProperties.removeNode(field);
                        it.Tag = null;
                        field = null;
                        FieldListView.Items.Remove(it);
                    }
                    SaveStatus = false;
                    FieldProperty.Visible = false;

                }
                moveing = false;
            }
        }

        private void FieldPopUpNode_Click(object sender, EventArgs e)
        {
            if (readOnly) return;
            moveing = true;
            if (FieldListView.SelectedItems.Count == 1)//字段上移
            {
                ListViewItem view = FieldListView.SelectedItems[0];
                BillUiFieldsItem field = view.Tag as BillUiFieldsItem;
                int index = FieldListView.Items.IndexOf(view);
                if (index > 0)
                {
                    dicBean.FieldsProperties.moveUp(field);
                    ListViewItem PevView = FieldListView.Items[index - 1];
                    PevView.Tag = dicBean.FieldsProperties.Fields[index - 1];
                    PevView.Text = (PevView.Tag as BillUiFieldsItem).Caption;
                    view.Tag = dicBean.FieldsProperties.Fields[index];
                    view.Text = (view.Tag as BillUiFieldsItem).Caption;
                    PevView.Selected = true;
                    view.Selected = false;
                    SaveStatus = false;
                }
            }
            moveing = false;
        }

        private void FieldPopDownNode_Click(object sender, EventArgs e)
        {
            if (readOnly) return;
            moveing = true;
            if (FieldListView.SelectedItems.Count == 1)//字段下移
            {
                ListViewItem view = FieldListView.SelectedItems[0];
                BillUiFieldsItem field = view.Tag as BillUiFieldsItem;
                int index = FieldListView.Items.IndexOf(view);
                if (index < FieldListView.Items.Count - 1)
                {
                    dicBean.FieldsProperties.moveDown(field);
                    ListViewItem LastView = FieldListView.Items[index + 1];
                    LastView.Tag = dicBean.FieldsProperties.Fields[index + 1];
                    LastView.Text = (LastView.Tag as BillUiFieldsItem).Caption;
                    view.Tag = dicBean.FieldsProperties.Fields[index];
                    view.Text = (view.Tag as BillUiFieldsItem).Caption;
                    LastView.Selected = true;
                    view.Selected = false;
                    SaveStatus = false;
                }
            }
            moveing = false;
        }

        private void FieldPopCheckAllNode_Click(object sender, EventArgs e)
        {
            moveing = true;
            FieldProperty.Visible = false;
            if (FieldListView.Items.Count > 0)
            {
                for (int i = 0; i < FieldListView.Items.Count; i++)
                {
                    ListViewItem it = FieldListView.Items[i];
                    it.Selected = true;
                }
            }
            moveing = false;
        }
    }




}
